package com.cet.designapplication.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;

import java.io.IOException;

/**
 * @author NSOC
 */
public class HttpClientUtils {

    private HttpClientUtils() {

    }

    public static JSONObject execute(String url, HttpMethod httpMethod) {
        HttpRequestBase httpRequestBase;
        try(CloseableHttpClient client = HttpClients.createDefault();) {
            if (httpMethod == HttpMethod.GET) {
                httpRequestBase = new HttpGet(url);
            } else {
                httpRequestBase = new HttpPost(url);
            }

            HttpEntity entity = client.execute(httpRequestBase).getEntity();
            return JSONObject.parseObject(EntityUtils.toString(entity));
        } catch (IOException e) {
            throw new RuntimeException("Request failed. url = " + url);
        }
    }
}
